<template>
    <el-row class="tac">
        <el-col :span="24">
            <el-menu default-active="2">
                <div v-for="(item, i) in menus" :key="item.id">
                    <el-sub-menu :index="item.index" v-if="item?.childs">
                        <template #title>
                            <el-icon>
                                <location />
                            </el-icon>
                            <span>{{ item.text }}</span>
                        </template>
                        <el-menu-item-group v-for="opt in item.childs" :key="opt.title" :title="opt.title">
                            <el-menu-item v-if="opt?.arr" v-for="obj in opt.arr" :key="obj.id" :index="obj.index"
                                @click="addTabEvent(obj.name, obj.id, obj.path)">
                                {{ obj.name }}
                            </el-menu-item>
                        </el-menu-item-group>
                    </el-sub-menu>
                    <el-menu-item :index="item.index" v-else @click="addTabEvent(item.name, item.id, item.path)">
                        <el-icon>
                            <component :is="item.icon"></component>
                        </el-icon>
                        <span>{{ item.text }}</span>
                    </el-menu-item>
                </div>
            </el-menu>
        </el-col>
    </el-row>
</template>

<script lang="ts" setup>
import {
    Menu as IconMenu,
    Location,
} from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute } from 'vue-router'
import { useMenuStore } from '../stores/menu'
import { useTabStore } from '../stores/tabBar'

const tabStore = useTabStore()
const menuStore = useMenuStore()
const { menus } = storeToRefs(menuStore)
const $router = useRouter()

const addTabEvent = (name: string, id: string, path: string) => {
    tabStore.add({ name, id, path })
    $router.push({ path })
}

const $route = useRoute()
const path = $route.path
const data = menus.value
const opt: any = {}

// 查找当前路径对应的菜单项
for (let i = 0; i < data.length; i++) {
    if (data[i].childs) {
        const childs = data[i].childs
        for (let j = 0; j < childs.length; j++) {
            if (childs[j].arr) {
                let arr = childs[j].arr
                for (let k = 0; k < arr.length; k++) {
                    if (arr[k].path === path) {
                        opt.name = data[i].name
                        opt.id = data[i].id
                        break
                    }
                }
            }
        }
    }
}
</script>